//
//  RtspViewController.m
//  RtspClient
//
//  Created by qi tan on 2024/1/3.
//  Copyright © 2024 Andres Rojas. All rights reserved.

#import <SystemConfiguration/CaptiveNetwork.h>
#import "RtspViewController.h"
#import "RTSPPlayer.h"
#import "GalleryViewController.h"
#import "GalleryImageController.h"
#import "GalleryVideosViewController.h"
#import "Constants.h"
#import "BeanGunTime.h"
#import "InstructTools.h"
#import "BeanGunZooming.h"
#import "BeanCurRange.h"
#import "BeanGunConfigIdx.h"
#import "BeanGunReticle.h"

#pragma mark - 宏定义常量
#define  kREQ_TYPE_GET 0
#define  kREQ_TYPE_SET 1

#define kTYPE_0 0
#define kTYPE_1 1
#define kTYPE_2 2
#define kTYPE_3 3
#define kTYPE_4 4
#define kTYPE_5 5
#define kTYPE_6 6
#define kTYPE_7 7

// 视频最长录制时间 120秒。
#define kVideoTimeMax 120


@interface RtspViewController ()
// 底部区域控制
@property (weak, nonatomic) IBOutlet UISegmentedControl *mSegement;
// 分别对应预览，分划，更多
@property (weak, nonatomic) IBOutlet UIView *mUIViewTab00;
@property (weak, nonatomic) IBOutlet UIView *mUIViewTab01;
@property (weak, nonatomic) IBOutlet UIView *mUIViewTab02;

// tab00 上的操作按钮
@property (weak, nonatomic) IBOutlet UIButton *mBtnVideoOnOff; // TODO 录像
@property (weak, nonatomic) IBOutlet UIButton *mBtnVideoSnap;
// 缓存zooming值。
@property (nonatomic, assign) double mCurrentZoom;
@property (nonatomic, assign) double mCurrentZoomTemp;
@property (weak, nonatomic) IBOutlet UIButton *mBtnZoomIn;
@property (weak, nonatomic) IBOutlet UIButton *mBtnZoomOut;

// tab01 主要UI元素。
@property (weak, nonatomic) IBOutlet UIButton *mBtnPreview; // 上一个枪
@property (weak, nonatomic) IBOutlet UIView *mViewNameEdit; // 名称整体布局
@property (weak, nonatomic) IBOutlet UIButton *mBtnName; // 名称按钮
@property (weak, nonatomic) IBOutlet UIButton *mBtnNext; // 下一个枪
@property (nonatomic, assign) int mGunIndex;
@property (nonatomic, strong) BeanGunConfigIdx *mConfigIdxBean;

// 分划颜色
@property (weak, nonatomic) IBOutlet UIButton *mBtnColor00;
@property (weak, nonatomic) IBOutlet UIButton *mBtnColor01;
@property (weak, nonatomic) IBOutlet UIButton *mBtnColor02;
@property (weak, nonatomic) IBOutlet UIButton *mBtnColor03;
@property (weak, nonatomic) IBOutlet UIButton *mBtnColor04;

// 分划模式
@property (weak, nonatomic) IBOutlet UIView *mModeNameBg;
@property (weak, nonatomic) IBOutlet UILabel *lblFenHuaModeName;

@property (weak, nonatomic) IBOutlet UIButton *mBtnMode00;
@property (weak, nonatomic) IBOutlet UIButton *mBtnMode01;
@property (weak, nonatomic) IBOutlet UIButton *mBtnMode02;
@property (weak, nonatomic) IBOutlet UIButton *mBtnMode03;
@property (weak, nonatomic) IBOutlet UIButton *mBtnMode04;
@property (weak, nonatomic) IBOutlet UIButton *mBtnMode05;
@property (weak, nonatomic) IBOutlet UIButton *mBtnMode06;


// 定时器: 视频播放View
@property (nonatomic, retain) NSTimer *nextFrameTimer;

/* 是否正在本地录像标记。 */
@property (nonatomic, assign) BOOL isVideoOnOff;
@property(nonatomic, retain) NSTimer *timer; // 自动录视频
@end



@implementation RtspViewController
@synthesize vodeo, imageView;
@synthesize nextFrameTimer = _nextFrameTimer;

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self showWifiApAlert]; // 提醒用户链接热点
    
    [self setTitle:NSLocalizedString(@"home", nil)];
    self.mUIViewTab01.hidden = YES;
    self.mUIViewTab02.hidden = YES;
    
    NSString *url = @"rtsp://192.168.8.1:554/livestream/1";
    video = [[RTSPPlayer alloc] initWithVideo:url usesTcp:false];
    video.outputWidth = 300 * 3; // 设置分辨率
    video.outputHeight = 225 * 3;
    self.vodeo = video;
    
    _nextFrameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/30 target:self selector:@selector(nextFrameTimer:) userInfo:nil repeats:YES];
    [_nextFrameTimer fire];
    
    
    // 获取默认的zoom信息。
    NSString *strUrl5 = [NSString stringWithFormat:@"%@%@", kInitURL, kURL_getqmzoom];
    [self sendHttpRequestWithUrl:strUrl5 andReqType:kREQ_TYPE_GET andType:kTYPE_5];
    
    // 处理tab01的初始化。获取强制索引。
    NSString *strUrl1 = [NSString stringWithFormat:@"%@%@", kInitURL, kURL_getqmguncfgidx];
    [self sendHttpRequestWithUrl:strUrl1 andReqType:kREQ_TYPE_GET andType:kTYPE_1];
    
    // 给分划模式的名称，设置背景。TODO
    self.mModeNameBg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_fenhua_name"]];
    
//    NSString *apName = [self getWifiSSID];
//    NSLog(@"wifi: %@", apName);
}


#pragma mark 系统默认弹框，提示用户连接热点。
- (void)showWifiApAlert {
    NSString *prompt = NSLocalizedString(@"prompt", nil);
    NSString *wifi_ap_alert =NSLocalizedString(@"wifi_ap_alert", nil);
    NSString *confirm =NSLocalizedString(@"confirm", nil);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:wifi_ap_alert preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:confirm style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
}




// 刷新视频的画面。
- (void)nextFrameTimer:(NSTimer *)timer
{
    if(!video.stepFrame) {
        [timer invalidate];
        [video closeAudio];
    }
    imageView.image = video.currentImage;
}



// 视频播放主界面。
- (IBAction)videoRecordOnOff:(id)sender {
//    if(self.isVideoOnOff ) {
//        [self.btnVideo setTitle:@"录屏结束" forState:UIControlStateNormal];
//    }else {
//        [self.btnVideo setTitle:@"开始结束" forState:UIControlStateNormal];
//    }
    self.isVideoOnOff = !self.isVideoOnOff;
    
    // 跳转页面
    GalleryViewController *gVC = [[GalleryViewController alloc] init];
    [self.navigationController pushViewController:gVC animated:YES];
}

#pragma mark 中间tab切换了
- (IBAction)segementChanged:(id)sender {
    int index = self.mSegement.selectedSegmentIndex;
    NSLog(@"select: %d", index);
    switch (index) {
        case 0:
            self.mUIViewTab00.hidden = NO;
            self.mUIViewTab01.hidden = YES;
            self.mUIViewTab02.hidden = YES;
            break;
        case 1:
            self.mUIViewTab00.hidden = YES;
            self.mUIViewTab01.hidden = NO;
            self.mUIViewTab02.hidden = YES;
            break;
        case 2:
            self.mUIViewTab00.hidden = YES;
            self.mUIViewTab01.hidden = YES;
            self.mUIViewTab02.hidden = NO;
            break;
        default:
            break;
    }
}

#pragma mark tab02的操作。相册，视频
- (IBAction)clickGallery:(id)sender {
//    GalleryViewController *gVC = [[GalleryViewController alloc] init];
    GalleryImageController *gVC = [[GalleryImageController alloc] init];
    [self.navigationController pushViewController:gVC animated:YES];
}

- (IBAction)clickGalleryVideo:(id)sender {
    NSLog(@"clickGalleryVideo");
    GalleryVideosViewController *gVC = [[GalleryVideosViewController alloc] init];
    [self.navigationController pushViewController:gVC animated:YES];
}


#pragma mark 开始录制视频
- (IBAction)clickVideoRecording:(id)sender {
    NSLog(@"clickVideoRecording %@", self.vodeo);
    // 点击录制视频。TODO
    if(self.isVideoOnOff) {
        // 停止录制视频。
        [self.mBtnVideoOnOff setImage:[UIImage imageNamed:@"video_default"] forState:UIControlStateNormal];
        [self.vodeo stopRrcordRtspVideo];
        
        // 停止轮训动作。
        [self.timer invalidate];
        self.timer = nil;
    } else {
        [self.vodeo startRecordRtspVideo];
        // 正在录制视频
        [self.mBtnVideoOnOff setImage:[UIImage imageNamed:@"video_recording"] forState:UIControlStateNormal];
        
        // 开始轮训动作, 分段录制
        self.timer = [NSTimer timerWithTimeInterval:kVideoTimeMax
                                             target:self
                                           selector:@selector(segementVideoRecording)
                                           userInfo:nil
                                            repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
    self.isVideoOnOff = !self.isVideoOnOff;
}

// 处理录像逻辑 saveRtspVideo TODO 处理关闭视频逻辑。

#pragma mark - 轮询执行的函数，用于分段录制视频
- (void)segementVideoRecording {
    // 停止录像；然后继续开启录像。
    if(self.isVideoOnOff) { // 录制中
        [self.vodeo stopRrcordRtspVideo];
        [self.vodeo startRecordRtspVideo];
    }
    NSLog(@"segementVideoRecording");
}




// 视频截图，保存到沙盒。
- (IBAction)clickVideoSnap:(id)sender {
    NSLog(@"视频截图");
    UIImage *image = video.currentImage; // 截图图片
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddRect(ctx, self.imageView.frame);
    CGContextClip(ctx);
    [image drawInRect: self.imageView.frame];
    // 保存UIImage到沙盒。
    
    // 获取doc路径
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    // 时间格式化
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
    [dateFormater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormater stringFromDate:[NSDate date]];
    NSString *fStr = [NSString stringWithFormat:@"%@.png", currentDateStr];
    NSLog(@"fstr= %@", fStr);
    // 获取文件路径
    NSString *filePath = [docPath stringByAppendingPathComponent:fStr];
    NSLog(@"filePath= %@", filePath);

    // 1.图片转成NSData,再将data写入到沙盒。
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:filePath atomically:YES];
    
    [self showAlert:NSLocalizedString(@"snap_success", nil)];
}

#pragma mark - tab01，点击事件监听。

// 修改名称。
- (IBAction)onClickName:(id)sender {
    [self showGunNameDialogWithIndex:self.mGunIndex];
}
// 上一个枪。
- (IBAction)onClickPreview:(id)sender {
    self.mGunIndex --;
    if(self.mGunIndex <= 0){
        self.mGunIndex =0;
    }
    [self onGunItemSelect];
}
- (IBAction)onClickNext:(id)sender {
    self.mGunIndex ++;
    if(self.mGunIndex >= 2) {
        self.mGunIndex =2;
    }
    [self onGunItemSelect];
}

// 更换枪支了
- (void)onGunItemSelect {
    self.mConfigIdxBean.gunIdx = [NSString stringWithFormat:@"%d", self.mGunIndex];
    
    self.mBtnNext.enabled = YES;
    self.mBtnPreview.enabled = YES;
    if(self.mGunIndex == 0) {
        [self.mBtnName setTitle:self.mConfigIdxBean.gunAlias0 forState:UIControlStateNormal];
        self.mBtnPreview.enabled = NO;
    } else if(self.mGunIndex == 1) {
        [self.mBtnName setTitle:self.mConfigIdxBean.gunAlias1 forState:UIControlStateNormal];
    } else {
        self.mBtnNext.enabled = NO;
        [self.mBtnName setTitle:self.mConfigIdxBean.gunAlias2 forState:UIControlStateNormal];
    }

    // 网络请求。
    [self setGunIdx:self.mGunIndex];
}

// 根据索引，获取索引对应的分划信息。
- (void)setGunIdx:(int)gunIdx {
    // 1.切换设备上的当前枪支
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setObject:[NSNumber numberWithInteger:self.mGunIndex] forKey:kKEY_gunIdx];
    // 索引的名称
    NSString *strURL = [InstructTools buildRtspSetInstruct:kInitURL
                                                 andSubUrl:kURL_setqmguncfgidx
                                              andParamDict:dict];
    // 中文字符转义处理。
//    NSString *url = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self sendHttpRequestWithUrl:strURL andReqType:kREQ_TYPE_SET andType:1];
    
    
    // 2. 根据强制，获取强制的分划信息。
    [self getGunReticleByGunIdx:[NSString stringWithFormat:@"%d", self.mGunIndex]];
}



// 根据枪支索引，修改名称。
- (void)showGunNameDialogWithIndex:(int)index {
    NSString *oldName = nil;
    if(index ==0) {
        oldName = self.mConfigIdxBean.gunAlias0;
    } else if(index ==1){
        oldName = self.mConfigIdxBean.gunAlias1;
    } else {
        oldName = self.mConfigIdxBean.gunAlias2;
    }
    // 弹出带输入框的对话框。
    NSString *prompt = NSLocalizedString(@"prompt", nil);
    NSString *enter_gun_name =NSLocalizedString(@"enter_gun_name", nil);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:enter_gun_name preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.text = oldName;
            textField.placeholder = enter_gun_name;
    }];
    // 确定，取消。confirm
    NSString *confirm =NSLocalizedString(@"confirm", nil);
    NSString *cancel = NSLocalizedString(@"cancel", nil);

    [alertController addAction:[UIAlertAction actionWithTitle:confirm style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *gunNameField = alertController.textFields.firstObject;
        NSString *inputName = gunNameField.text;
        NSLog(@"gun name: %@", inputName);
        if([inputName isEqualToString:@""]) {
            // 未输入内容。 enter_name
            [self showAlert:NSLocalizedString(@"enter_name", nil)];
        } else { // 输入了内容,传输给设备。
            [self.mBtnName setTitle:inputName forState:UIControlStateNormal];
            [self setGunAliasNameWithIndex:index andNewName:inputName];
            
            // 更新本地缓存
            if(index == 0) {
                self.mConfigIdxBean.gunAlias0 = inputName;
            } else if (index == 1) {
                self.mConfigIdxBean.gunAlias1 = inputName;
            } else {
                self.mConfigIdxBean.gunAlias2 = inputName;
            }
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 传值给设备。修改a/b/c枪支的名称
- (void)setGunAliasNameWithIndex:(int)index andNewName:(NSString *)name {
    NSMutableDictionary *dict = [NSMutableDictionary new];
    if(index == 0) {
        [dict setObject:name forKey:kKEY_gunAlias0];
    } else if(index == 1) {
        [dict setObject:name forKey:kKEY_gunAlias1];
    } else {
        [dict setObject:name forKey:kKEY_gunAlias2];
    }
    // 索引的名称
    NSString *strURL = [InstructTools buildRtspSetInstruct:kInitURL
                                                 andSubUrl:kURL_setqmguncfgidx
                                              andParamDict:dict];
    // 中文字符转义处理。
    NSString *url = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self sendHttpRequestWithUrl:url andReqType:kREQ_TYPE_SET andType:1];
}


// 刷新分划线UI
#pragma mark - 颜色选择事件。
- (IBAction)color00Clicked:(id)sender {
    [self resetColorItems];
    [self.mBtnColor00 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    [self setColorOrMode:kKEY_color andValue:0];
}
- (IBAction)color01Clicked:(id)sender {
    [self resetColorItems];
    [self.mBtnColor01 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    [self setColorOrMode:kKEY_color andValue:1];
}
- (IBAction)color02Clicked:(id)sender {
    [self resetColorItems];
    [self.mBtnColor02 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    [self setColorOrMode:kKEY_color andValue:2];
}
- (IBAction)color03Clicked:(id)sender {
    [self resetColorItems];
    [self.mBtnColor03 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    [self setColorOrMode:kKEY_color andValue:3];
}
- (IBAction)color04Clicked:(id)sender {
    [self resetColorItems];
    [self.mBtnColor04 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    [self setColorOrMode:kKEY_color andValue:4];
}
#pragma mark -  模式选择事件。
- (IBAction)mode00Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode00 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_mwd", nil);
    [self setColorOrMode:kKEY_mode andValue:0];
}
- (IBAction)mode01Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode01 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_sx", nil);
    [self setColorOrMode:kKEY_mode andValue:1];
}
- (IBAction)mode02Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode02 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_hzd", nil);
    [self setColorOrMode:kKEY_mode andValue:2];
}
- (IBAction)mode03Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode03 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_zxd", nil);
    [self setColorOrMode:kKEY_mode andValue:3];
}
// 第二行。
- (IBAction)mode04Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode04 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_szj", nil);
    [self setColorOrMode:kKEY_mode andValue:4];
}
- (IBAction)mode05Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode05 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_kfsz", nil);
    [self setColorOrMode:kKEY_mode andValue:5];
}
- (IBAction)mode06Clicked:(id)sender {
    [self resetModeItems];
    [self.mBtnMode06 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
    self.lblFenHuaModeName.text = NSLocalizedString(@"type_xc", nil);
    
    [self setColorOrMode:kKEY_mode andValue:6];
}

// 传入key和value，设置给设备。
- (void)setColorOrMode:(NSString *)key andValue:(int)value {
    NSMutableDictionary *dict = [NSMutableDictionary new];
    // 传入当前枪支的index
    [dict setObject:[NSNumber numberWithInteger:self.mGunIndex] forKey:kKEY_gunIdx];
    // 分划模式，颜色
    [dict setObject:[NSNumber numberWithInteger:value] forKey:key];
    
    NSString *strURL = [InstructTools buildRtspSetInstruct:kInitURL
                                                 andSubUrl:kURL_setqmreticle
                                              andParamDict:dict];
    [self sendHttpRequestWithUrl:strURL andReqType:kREQ_TYPE_SET andType:2];
}




#pragma mark - 重置颜色和模式选择。
- (void)resetColorItems {
    [self.mBtnColor00 setImage:nil forState:UIControlStateNormal];
    [self.mBtnColor01 setImage:nil forState:UIControlStateNormal];
    [self.mBtnColor02 setImage:nil forState:UIControlStateNormal];
    [self.mBtnColor03 setImage:nil forState:UIControlStateNormal];
    [self.mBtnColor04 setImage:nil forState:UIControlStateNormal];
}
- (void)resetModeItems {
    [self.mBtnMode00 setBackgroundImage:nil forState:UIControlStateNormal];
    [self.mBtnMode01 setBackgroundImage:nil forState:UIControlStateNormal];
    [self.mBtnMode02 setBackgroundImage:nil forState:UIControlStateNormal];
    [self.mBtnMode03 setBackgroundImage:nil forState:UIControlStateNormal];
    [self.mBtnMode04 setBackgroundImage:nil forState:UIControlStateNormal];
    [self.mBtnMode05 setBackgroundImage:nil forState:UIControlStateNormal];
    [self.mBtnMode06 setBackgroundImage:nil forState:UIControlStateNormal];
}


#pragma mark - 焦距改变

// 焦距改变。
- (IBAction)clickZoomIn:(id)sender {
    NSLog(@"clickZoomIn");
    [self setGunZoomRate:YES]; // 放大
}

- (IBAction)clickZoomOut:(id)sender {
    NSLog(@"clickZoomOut");
    [self setGunZoomRate:NO]; // 缩小
}

#pragma mark - 处理发送给设备的Zoom值。
// TODO
- (void)setGunZoomRate:(BOOL)isZoomIn {
    double newZoomRate = self.mCurrentZoom;
    [self.mBtnZoomIn setEnabled:YES];
    [self.mBtnZoomOut setEnabled:YES];
    
    if(isZoomIn) {
        newZoomRate += 0.5;
        if(newZoomRate >= 4.0) {
            newZoomRate = 4.0;
            [self.mBtnZoomIn setEnabled:NO];
        }
    } else { // 缩小
        newZoomRate -= 0.5;
        if(newZoomRate <= 1.0) {
            newZoomRate = 1.0;
            [self.mBtnZoomOut setEnabled:NO];
        }
    }
    if(self.mCurrentZoom == newZoomRate) {
        NSLog(@"mCurrentZoom, newZoomRate are the same!!!");
        return; // 未发生改变
    }
    NSLog(@"mCurrentZoom, %f", newZoomRate);

    self.mCurrentZoomTemp = newZoomRate;
    [self  setGunZoomValue: self.mCurrentZoomTemp];
}

// 给设备设置焦距
- (void)setGunZoomValue:(double)zoom {
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setObject:[NSNumber numberWithDouble:zoom] forKey:kKEY_zoomRate]; // 焦距
    NSString *strURL = [InstructTools buildRtspSetInstruct:kInitURL
                                                 andSubUrl:kURL_setqmzoom
                                              andParamDict:dict];
    [self sendHttpRequestWithUrl:strURL andReqType:kREQ_TYPE_SET andType:5];
}








#pragma mark - 给设备发送http请求
// 发送请求给设备。
- (void)sendHttpRequestWithUrl:(NSString *)urlStr andReqType:(int)reqType andType:(int)type {
    NSLog(@"sendHttpRequestWithUrl: %@", urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 发送异步请求，获取反馈的结果。
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // response，data，error
        if(!connectionError) {// 请求是否有错误
            int code = connectionError.code;
            // 二进制数据转成NSString
            NSString  *html = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
            // NSLog(@"result:%d, %@", code, html);

            // 返回的数据。
            [self httpResponseWithReqType:reqType andType:type andCode:code andResult:html];
            
        } else {
            NSLog(@"连接错误 %@",connectionError);
        }
    }];
}

// 处理设备返回的结果。
- (void)httpResponseWithReqType:(int)reqType andType:(int)type andCode:(int)code andResult:(NSString *)result {
    NSLog(@"reqType:%d, type:%d, code:%d, result:%@====", reqType, type, code, result);
    if(reqType == kREQ_TYPE_GET) {
        // 读取数据
        NSString *payLoad = result;
        if([payLoad containsString:@"Success"]) {
            NSRange range = [payLoad rangeOfString:@"Success"];
            range.length = range.location;
            range.location = 0;
            payLoad = [payLoad substringWithRange:range];
        } else if([payLoad containsString:@"SvrFuncResult"]) {
            // 截取前面的内容
            NSRange range = [payLoad rangeOfString:@"SvrFuncResult"];
            payLoad = [payLoad substringToIndex:range.location];
        }
        
        @try {
            NSMutableDictionary *dict = [self dictionaryWithDeviceString:payLoad];
            if(type == kTYPE_5) {
                BeanGunZooming *gunZoomingBean = [BeanGunZooming beanWithDict:dict];
                if(gunZoomingBean != nil) {
                    self.mCurrentZoom = gunZoomingBean.zoomRate;
                    NSLog(@"zoom is: %f", self.mCurrentZoom);
                    
                }
            } else if(type == kTYPE_1) {
                // 获取强制信息了
                self.mConfigIdxBean = [BeanGunConfigIdx beanWithDict:dict];
                if (self.mConfigIdxBean != nil) {
                    NSLog(@"%@", self.mConfigIdxBean);
                    [self setGunNameWithBean:self.mConfigIdxBean];
                }
            } else if (type == kTYPE_2) {
                // 根据索引，获取的
                BeanGunReticle *gunReticle = [BeanGunReticle beanWithDict:dict];
                [self showDeviceModeColor:gunReticle];
            }
            
        } @catch (NSException *exception) {
            NSLog(@"%@, %@",exception.name, exception.reason);
        }
   } else {
       // 设置数据  "operate_success"="Operation successful";
       result = [result stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
       if([result isEqualToString:@"Success"]) {
           [self showAlert:NSLocalizedString(@"operate_success", nil)];
       } else {
           [self showAlert:NSLocalizedString(@"operate_fail", nil)];
       }
       if(type == kTYPE_5) {
           self.mCurrentZoom = self.mCurrentZoomTemp;
           NSLog(@"current zoom: %f", self.mCurrentZoom);
       }
       NSLog(@"-%@-",result);
   }
}

// 初始化显示设备上的模式，颜色信息
- (void) showDeviceModeColor:(BeanGunReticle *)gunRecticle {
    if([gunRecticle.color isEqualToString:@"0"]) {
        [self.mBtnColor00 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    } else if([gunRecticle.color isEqualToString:@"1"]) {
        [self.mBtnColor01 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];

    } else if([gunRecticle.color isEqualToString:@"2"]) {
        [self.mBtnColor02 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];

    } else if([gunRecticle.color isEqualToString:@"3"]) {
        [self.mBtnColor03 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];

    } else if([gunRecticle.color isEqualToString:@"4"]) {
        [self.mBtnColor03 setImage:[UIImage imageNamed:@"icon_focus"] forState:UIControlStateNormal];
    }
    // 模式。
    if([gunRecticle.mode isEqualToString:@"0"]) {
        [self.mBtnMode00 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_mwd", nil);
    } else if([gunRecticle.mode isEqualToString:@"1"]) {
        [self.mBtnMode01 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_sx", nil);
    } else if([gunRecticle.mode isEqualToString:@"2"]) {
        [self.mBtnMode02 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_hzd", nil);
    } else if([gunRecticle.mode isEqualToString:@"3"]) {
        [self.mBtnMode03 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_zxd", nil);
    } else if([gunRecticle.mode isEqualToString:@"4"]) {
        [self.mBtnMode04 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_szj", nil);
    } else if([gunRecticle.mode isEqualToString:@"5"]) {
        [self.mBtnMode05 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_kfsz", nil);
    } else if([gunRecticle.mode isEqualToString:@"6"]) {
        // 选中图标。
        [self.mBtnMode06 setBackgroundImage:[UIImage imageNamed:@"bg_gun_name"] forState:UIControlStateNormal];
        self.lblFenHuaModeName.text = NSLocalizedString(@"type_xc", nil);
    }
}



// 设置显示的枪名称
- (void)setGunNameWithBean:(BeanGunConfigIdx *) beanInfo {
    if([@"1" isEqualToString:beanInfo.gunIdx]) {
        self.mBtnPreview.enabled = YES;
        self.mBtnNext.enabled = YES;
        [self.mBtnName setTitle:beanInfo.gunAlias1 forState:UIControlStateNormal];
        self.mGunIndex = 1;
    } else if([@"2" isEqualToString:beanInfo.gunIdx]) {
        self.mBtnPreview.enabled = YES;
        self.mBtnNext.enabled = NO;
        [self.mBtnName setTitle:beanInfo.gunAlias2 forState:UIControlStateNormal];
        self.mGunIndex = 2;
    } else { // 0
        self.mBtnPreview.enabled = NO;
        self.mBtnNext.enabled = YES;
        [self.mBtnName setTitle:beanInfo.gunAlias0 forState:UIControlStateNormal];
        self.mGunIndex = 0;
    }
    // 请求枪支对应的分划线信息。
    [self getGunReticleByGunIdx:beanInfo.gunIdx];
}

// 根据id 获取枪支的分划信息，更新UI。
- (void)getGunReticleByGunIdx:(NSString *)gunIdx {
   [self resetColorItems];
   [self resetModeItems];
    
    // 获取枪支的分划信息。
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setObject:gunIdx forKey:kKEY_gunIdx]; // 枪支索引。
    NSString *strURL2 = [InstructTools buildRtspSetInstruct:kInitURL
                                                 andSubUrl:kURL_getqmreticle
                                              andParamDict:dict];
    [self sendHttpRequestWithUrl:strURL2 andReqType:kREQ_TYPE_GET andType:kTYPE_2];
}


#pragma mark - 转变成字典数据
// 转变成字典数据
// eg: var time="20240106174920"; var timeformat="0"; var timezone="";
- (NSMutableDictionary *)dictionaryWithDeviceString:(NSString *)jsonString {
    if(jsonString == nil) return nil;
    
   //  jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    // 按照分号，切割字符串。
    NSArray * array = [jsonString  componentsSeparatedByString:@";"];
    // NSLog(@"length:%d", array.count);
    NSMutableDictionary * dict1 = [NSMutableDictionary new];
    for (int i=0; i<array.count; i++) {
        NSString *item = [array objectAtIndex:i]; // 每个属性字段
        
        if(![item isEqualToString:@"\r\n"]) {
//            NSLog(@"---------\n item: %@", item);
            NSRange range = [item rangeOfString:@"var "];
            NSRange rangeEqual = [item rangeOfString:@"="];
//            NSLog(@"range:%d, %d", range.location, range.length);
//            NSLog(@"range2：%d, %d", rangeEqual.location, rangeEqual.length);

            // 获取key(根据‘var ’的位置，'='的位置计算出来)，要考虑里面有'\r\n'的情况
            NSRange rangeK = NSMakeRange(range.location + range.length,
                                         rangeEqual.location - range.length - range.location);
            NSString * key = [item substringWithRange:rangeK];
            NSString * value = [item substringFromIndex:rangeEqual.location +1];
            // 去掉双引号
            value = [value stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            // NSLog(@"result item: key=%@, value=%@", key, value);
            [dict1 setObject:value forKey:key];
        }
    }
    return dict1;
}

#pragma mark - Toast弹框
- (void)showAlert:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [self performSelector:@selector(dismiss:) withObject:alertController afterDelay:2.0];
}
- (void)dismiss:(UIAlertController *)alert {
    [alert dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 获取手机wifi_SSID
- (NSString *)getWifiSSID {
    NSString *ssid = nil;
    CFArrayRef arrRef = CNCopySupportedInterfaces();
    NSArray *ifs = (__bridge id)arrRef;
    for (NSString *ifnam in ifs) {
        CFDictionaryRef dicRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSDictionary *info = (__bridge id)dicRef;
        if (info[@"BSSID"]) {
            ssid = info[@"SSID"];
        }
        if(dicRef !=nil) {
            CFRelease(dicRef);
        }
    }
    if(arrRef != nil) {
        CFRelease(arrRef);
    }
    return ssid;
}




@end
